package com.etrans.web.gps.business.report.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.report.domain.NightDriving2To5VO;
import com.etrans.web.gps.business.report.service.NightDriving2To5Service;
import com.etrans.web.gps.business.system.domain.SysUser;
import com.etrans.web.gps.business.system.service.CommonService;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.util.Config;
import com.etrans.web.gps.util.grid.FlexiGridUtil;

@Controller
@RequestMapping("/report/nightDriving2To5/*")
public class NightDriving2To5Controller extends BaseController{
	
	private final static Logger logger = LoggerFactory.getLogger(NightDriving2To5Controller.class);
	@Autowired
	private NightDriving2To5Service nightDriving2To5Service;
	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private Config config; //引用统一的参数配置类 
	

	@RequestMapping("analyse.html")
	public String vehicleDrivingAnaOpen(){
		return "views/business/report/nightDriving2To5Ana";
	}
	
	/**
	 * 查询登录用户权限下的全部的车辆
	 * @param area_id 区域编号   
	 * @return  车辆所有信息
	 */
	@ResponseBody
	@RequestMapping("queryVehicleListByRole.html")
	public  List<HashMap<String,Object>> queryVesByRoleAndKind(HttpServletRequest request){
		String name = request.getParameter("name");
		HashMap<String,Object> params = new HashMap<String,Object>();
		SysUser user = getSysUser();
		params.put("fullID", user.getFullID());
		params.put("selected", "selected");
		params.put("vehicle_no", name);
		return commonService.queryVeListByRole(params);
	}
	
	/**
	 * 查询登录用户权限下的业户
	 * @return  业户信息列表
	 */
	@ResponseBody
	@RequestMapping("getEnterpirseList.html")
	public  List<HashMap<String,Object>> getEnterpirseList(){
		int area_id= this.getSysUser().getArea_id();
		return nightDriving2To5Service.queryEnterAndPlatByRole(area_id);
	}
	/**
	 * 初始化查询夜间2点到5点行车分析报表数据
	 * @param vehicleId 车辆ID
	 * @param startTime 查询开始时间
	 * @param endTime 查询结束时间
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getBarChartData.html")
	public Map<String,Object> getBarChartData(){
		Map<String,Object> resultMap =new HashMap<String, Object>();
		//权限下的所有业户
		int area_id= this.getSysUser().getArea_id();
		List<String> entNameList = new ArrayList<String>();
		List<HashMap<String,Object>> queryList =nightDriving2To5Service.queryEnterAndPlatByRole(area_id);
		for (HashMap<String, Object> entMap : queryList) {
			entNameList.add(String.valueOf(entMap.get("entName")));
		}
		List<String>  xAxisData =new ArrayList<String>();
		List<Integer>  SeriesData =new ArrayList<Integer>();
		//获取查询条件
		Map<String,Object> params = getReqParameters();
		String queryChose = (String) params.get("queryChose") == null || "".equals(String.valueOf(params.get("queryChose")))  
				? "0":String.valueOf(params.get("queryChose"));
		String vehicle_no = (String) params.get("vehicle_no") == null || "".equals(String.valueOf(params.get("vehicle_no")))  
				? "0":String.valueOf(params.get("vehicle_no"));
		String enterprise_name = (String) params.get("enterprise_name") == null || "".equals(String.valueOf(params.get("enterprise_name")))  
				? "0": String.valueOf(params.get("enterprise_name"));
		String start_time = String.valueOf(params.get("startTime")) == null || "".equals(String.valueOf(params.get("startTime")))  
				? "0": String.valueOf(params.get("startTime"));
		String end_time = String.valueOf(params.get("endTime")) == null || "".equals(String.valueOf(params.get("endTime")))  
				? "0": String.valueOf(params.get("endTime"));
		//判断查询类型分别查询
		if (!"0".equals(start_time) && !"0".equals(end_time)) {
			Date startTime = new Date(Long.valueOf(start_time));
			Date endTime = new Date(Long.valueOf(end_time));
			if ("ent".equals(queryChose)) {
				if ( !"0".equals(enterprise_name)) {
					Integer alarmVeCount =nightDriving2To5Service.queryNightDriCountByEnt(enterprise_name, startTime,endTime);
					xAxisData.add(enterprise_name);
					SeriesData.add(alarmVeCount);
				}else{
					List<Object> list = nightDriving2To5Service.queryNightDrivingCount(startTime, endTime);
					if (list.size()>0) {
						for (Object obj : list) {
							String jsonStr = JSONObject.toJSONString(obj);
							JSONObject json = JSON.parseObject(jsonStr);
							String name = String.valueOf(json.get("_id"));
							if (entNameList.contains(name)) {
								xAxisData.add(name);
								SeriesData.add(Integer.parseInt(String.valueOf(json.get("count"))));
							}
						}
					}else {
						xAxisData.add("");
						SeriesData.add(0);
					}
				}
			}
			if ("veh".equals(queryChose)) {
				if ( !"0".equals(vehicle_no)) {
					//按车牌号查询
					HashMap<String,Object> vehicle = commonService.queryVehicleByVeNo(vehicle_no);
					String enterpriseName = (String) vehicle.get("enterprise_name");
					Integer alarmVeCount =nightDriving2To5Service.queryNightDriCountByEnt(enterpriseName, startTime,endTime);
					xAxisData.add(enterpriseName);
					SeriesData.add(alarmVeCount);
				}else {
					//按业户查询全部车辆
					List<Object> list = nightDriving2To5Service.queryNightDrivingCount(startTime, endTime);
					if (list.size()>0) {
						for (Object obj : list) {
							String jsonStr = JSONObject.toJSONString(obj);
							JSONObject json = JSON.parseObject(jsonStr);
							String name = String.valueOf(json.get("_id"));
							if (entNameList.contains(name)) {
								xAxisData.add(name);
								SeriesData.add(Integer.parseInt(String.valueOf(json.get("count"))));
							}
						}
					}else {
						xAxisData.add("");
						SeriesData.add(0);
					}
				}
			}
		}
		resultMap.put("xAxisData", xAxisData);
		resultMap.put("series", SeriesData);
		resultMap.put("start_time", start_time);
		resultMap.put("end_time", end_time);
		resultMap.put("address_Path", config.addressPath);
        return resultMap;
	}
	
	
	/**
	 * 根据业户名和查询时间查询
	 * @return  登录用户权限下的全部业户的旅游异动车辆
	 */
	@ResponseBody
	@RequestMapping(value = "getResultTableByEnt.html")
	public PageVo getResultTableByEnt(){
		PageVo pageVo = new PageVo();
		//权限下的所有业户
		int area_id= this.getSysUser().getArea_id();
		List<Integer> entIdList =nightDriving2To5Service.queryEnterIdListByRole(area_id);
		List<NightDriving2To5VO> resultList = new ArrayList<NightDriving2To5VO>();
		List<NightDriving2To5VO> nightVeList = null;
		Integer total = 0;
		//获取车辆颜色Map
		Map<String,Object> colorMap = new HashMap<String,Object>();
		List<HashMap<String, Object>> colorList = commonService.queryVehicleColorList(null);
		for (HashMap<String, Object> hashMap : colorList) {
			colorMap.put(String.valueOf(hashMap.get("id")), hashMap.get("name"));
		}
		//获取查询条件
		Map<String,Object> paramMaps = getReqParameters();
		String paramsGrid = String.valueOf(paramMaps.get("paramsGrid"));
		Map<String, Object> params = FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
		Integer pageSize = Integer.parseInt(String.valueOf(params.get("pageSize")));
		Integer page = Integer.parseInt(String.valueOf(params.get("page")));
		String queryChose = (String) params.get("queryChose") == null || "".equals(String.valueOf(params.get("queryChose")))  
				? "0":String.valueOf(params.get("queryChose"));
		String vehicle_no = (String) params.get("vehicle_no") == null || "".equals(String.valueOf(params.get("vehicle_no")))  
				? "0":String.valueOf(params.get("vehicle_no"));
		String enterprise_name = (String) params.get("enterprise_name") == null || "".equals( String.valueOf(params.get("enterprise_name")))  
				? "0": String.valueOf(params.get("enterprise_name"));
		String start_time = String.valueOf(params.get("startTime")) == null || "".equals(String.valueOf(params.get("startTime")))  
				? "0": String.valueOf(params.get("startTime"));
		String end_time = String.valueOf(params.get("endTime")) == null || "".equals(String.valueOf(params.get("endTime")))  
				? "0": String.valueOf(params.get("endTime"));
		if ( !"0".equals(start_time) &&  !"0".equals(end_time)) {
			Date startTime = new Date(Long.valueOf(start_time));
			Date endTime = new Date(Long.valueOf(end_time));
			if ("ent".equals(queryChose)) {
				if (!"0".equals(enterprise_name)) {
					total = nightDriving2To5Service.queryNightDriCountByEnt(enterprise_name,startTime,endTime);
					nightVeList = nightDriving2To5Service.getResultTableByByEnt(enterprise_name,startTime,endTime,page,pageSize);
				}else{
					total = nightDriving2To5Service.queryNightAllCountByRole(entIdList,startTime,endTime);
					nightVeList = nightDriving2To5Service.getAllResultTableByByRole(entIdList,startTime,endTime,page,pageSize);
				}
			}
			if ("veh".equals(queryChose)) {
				if (!"0".equals(vehicle_no)) {
					nightVeList = nightDriving2To5Service.getResultTableByNo(vehicle_no,startTime,endTime,page,pageSize);
					total = nightVeList.size();
				}else{
					total = nightDriving2To5Service.queryNightAllCountByRole(entIdList,startTime,endTime);
					nightVeList = nightDriving2To5Service.getAllResultTableByByRole(entIdList,startTime,endTime,page,pageSize);
				}
			}
			Integer index = (page - 1)*pageSize+1;
			if (nightVeList != null && nightVeList.size() > 0) {
				for (NightDriving2To5VO nightDriving : nightVeList) {
					nightDriving.setIndex(index++);
					String colorId = String.valueOf(nightDriving.getVehicle_color());
					nightDriving.setVehicle_color_name(String.valueOf(colorMap.get(colorId)));
					resultList.add(nightDriving);
				}
			}
		}
		pageVo.setTotal(total);
		pageVo.setRows(resultList);
		pageVo.setPage(page);
        return pageVo;
	}
	
	/**
	 * 导出报表
	 * @param response
	 * @param request
	 * @param paramsGrid 前端json格式的参数
	 * @param colModel 表头
	 * @param title 标题
	 * @param imgsrc 图片url,如果为null则不加载图片页
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value="exportResultTable.html")
	@ResponseBody
	public void exportDriver(HttpServletResponse response,HttpServletRequest request, String queryChose ,String vehicle_no,String enterprise_name, String colModel,
			String start_time,String end_time ,String pagesize,String StartPage,String EndPage,String title,String imgsrc){
		List<String> colModelList = JSON.parseObject(colModel, List.class);	
		List<String> imgsrcList   = JSON.parseObject(imgsrc, List.class);
		//权限下的所有业户
		int area_id= this.getSysUser().getArea_id();
		List<Integer> entIdList =nightDriving2To5Service.queryEnterIdListByRole(area_id);
		List<NightDriving2To5VO> resultList = new ArrayList<NightDriving2To5VO>();
		List<NightDriving2To5VO> nightVeList = null;
		//获取车辆颜色Map
		Map<String,Object> colorMap = new HashMap<String,Object>();
		List<HashMap<String, Object>> colorList = commonService.queryVehicleColorList(null);
		for (HashMap<String, Object> hashMap : colorList) {
			colorMap.put(String.valueOf(hashMap.get("id")), hashMap.get("name"));
		}
		Integer pageSize = Integer.parseInt(pagesize)*(Integer.parseInt(EndPage)-Integer.parseInt(StartPage)+1);
		Integer page = Integer.parseInt(StartPage);
		queryChose = queryChose == null || "".equals(queryChose)  
				? "0":queryChose;
		vehicle_no = vehicle_no == null || "".equals(vehicle_no)  
				? "0":vehicle_no;
		enterprise_name = enterprise_name == null || "".equals( enterprise_name)  
				? "0": enterprise_name;
		start_time = start_time == null || "".equals(start_time)  
				? "0": start_time;
		end_time = end_time == null || "".equals(end_time)  
				? "0": end_time;
		if ( !"0".equals(start_time) &&  !"0".equals(end_time)) {
			Date startTime = new Date(Long.valueOf(start_time));
			Date endTime = new Date(Long.valueOf(end_time));
			if ("ent".equals(queryChose)) {
				if (!"0".equals(enterprise_name)) {
					nightVeList = nightDriving2To5Service.getResultTableByByEnt(enterprise_name,startTime,endTime,page,pageSize);
				}else{
					nightVeList = nightDriving2To5Service.getAllResultTableByByRole(entIdList,startTime,endTime,page,pageSize);
				}
			}
			if ("veh".equals(queryChose)) {
				if (!"0".equals(vehicle_no)) {
					nightVeList = nightDriving2To5Service.getResultTableByNo(vehicle_no,startTime,endTime,page,pageSize);
				}else{
					nightVeList = nightDriving2To5Service.getAllResultTableByByRole(entIdList,startTime,endTime,page,pageSize);
				}
			}
			Integer index = (page - 1)*pageSize+1;
			if (nightVeList != null && nightVeList.size() > 0) {
				for (NightDriving2To5VO nightDriving : nightVeList) {
					nightDriving.setIndex(index++);
					String colorId = String.valueOf(nightDriving.getVehicle_color());
					nightDriving.setVehicle_color_name(String.valueOf(colorMap.get(colorId)));
					resultList.add(nightDriving);
				}
			}
		}
		List<HashMap<String, Object>> rows = new ArrayList<HashMap<String, Object>>();
		for(int i=0;i<resultList.size();i++){
			HashMap<String, Object> map = new HashMap<String, Object>();
			NightDriving2To5VO  nightDriving=(NightDriving2To5VO)resultList.get(i);
			map.put("index",nightDriving.getIndex() == null ? "" : nightDriving.getIndex());
			map.put("vehicle_no",nightDriving.getVehicle_no()== null ? "" : nightDriving.getVehicle_no());
			map.put("vehicle_color_name",nightDriving.getVehicle_color_name() == null ? "" : nightDriving.getVehicle_color_name());
			map.put("enterprise_name",nightDriving.getEnterprise_name() == null ? "" : nightDriving.getEnterprise_name());
			map.put("coordinates_two",nightDriving.getCoordinates_two() == null ? "" : getLocation(nightDriving.getCoordinates_two()));
			map.put("coordinates_five",nightDriving.getCoordinates_five() == null ? "" : getLocation(nightDriving.getCoordinates_five()));
			map.put("mileage_2_5",nightDriving.getMileage_2_5() == null ? "" : nightDriving.getMileage_2_5());
			rows.add(map);
		}	
		List rowsList = new ArrayList<>();
		rowsList.add(rows);
		exportExl(request, response,title, removeHeadName(colModelList,-1,-1),rowsList,imgsrcList);
	}
	
	/**
	 * 根据经纬度获取地理位置
	 * @param jsonObject 经纬度
	 * @return           地理位置
	 */
	public  String getLocation(JSONObject jsonObject){
		StringBuffer buff = new StringBuffer();
		String URL =config.addressPath+"?location="+JSON.parseArray(String.valueOf(jsonObject.get("coordinates"))).get(0)+","+JSON.parseArray(String.valueOf(jsonObject.get("coordinates"))).get(1);
		HttpPost httpPost = new HttpPost(URL);
		CloseableHttpClient client = HttpClientBuilder.create().build();
		String str =null;
		try {
			HttpResponse response = client.execute(httpPost);
			InputStream in = response.getEntity().getContent();
			InputStreamReader isr = new InputStreamReader(in);
			BufferedReader bfr =new  BufferedReader(isr);
			while((str=bfr.readLine())!=null){
				buff.append(str);
			}
			bfr.close();
			JSONObject json = JSONObject.parseObject(buff.toString());
			str = json.get("regeocodes").toString();
			str = str.substring(1,str.length()-1);
			json = JSONObject.parseObject(str);
			str = json.get("formatted_address").toString();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("导出位置获取失败",e);
		}
		return str;
	}
}
